#!/usr/bin/python3
# -*- coding:utf-8 -*-
import asyncio
import json
import os.path

from channels.generic.websocket import AsyncWebsocketConsumer
import time
from djangoProject.settings import BASE_DIR
from markdown.src import jvm_tool
from job.src.function.record_log import mylog
from markdown.src import luckysheet_update

class SheetConsumer(AsyncWebsocketConsumer):
    def __init__(self):
        super(SheetConsumer, self).__init__()
        self.res_data = {
                "createTime": time.ctime(), # 命令发送时间
                "data": {},                 # 修改的命令
                "id": "",                   # websocket的id
                "returnMessage": "success",
                "status": "0",    # 0告诉前端需要根据data的命令修改  1无意义
                "type": 0,        # 0：连接成功，1：发送给当前连接的用户，2：发送信息给其他用户，3：发送选区位置信息（就是会出现边框显示，显示名称的），999：用户连接断开
                "username": "",   # 用户名
            }

    async def connect(self):
        mylog.warn(self.scope['url_route'])
        self.sheet = self.scope['url_route']['kwargs']['filename']
        self.sheet_name = "sheet:" + self.sheet
        self.sheet_group_name = 'sheet_%s' % self.sheet
        self.user = self.scope['user']
        mylog.info(f"{self.user},connect ok;open file {self.sheet}")
        mylog.info(f'组名：{self.sheet_group_name}')

        # Join sheet group // first: 文件名作为组名； second：用户名作为channel_name;
        await self.channel_layer.group_add(
            self.sheet_group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        self.room_name = self.scope['url_route']['kwargs']['filename']
        mylog.info(f"{self.user},disconnect ok")
        # Leave room group
        await self.channel_layer.group_discard(
            self.sheet_group_name,
            self.channel_name
        )
        await self.close()

    async def receive(self, text_data=None, bytes_data=None):
        # 接收数据后的中间出了过程，更新redis的数据
        dep_data = self.unGzip(text_data)

        # Send message to room group
        await self.channel_layer.group_send(
            self.sheet_group_name,
            {
                'type': 'chat_message',
                'message': dep_data
            }
        )

    # Receive message from room group
    async def chat_message(self, event):
        # mylog.info(f"触发单点发送消息,{self.channel_name}")
        message = event['message']

        # Send message to WebSocket单发消息
        await self.send(text_data=json.dumps(message))

    def unGzip(self, data):
        '''
        处理websocket发送过来的信息，前端是将数据通过gzip压缩后发送过来的，所以理由java包的函数来解压数据。
        :param data:
        :return:
        '''
        if 'rub' in data:
            dep_data = {
                "data": "rub",
                "returnMessage": "success",
            }
        else:
            jpy = jvm_tool.jpython_obj
            res = jpy.unCompressURI(data)
            res = json.loads(str(res))
            # mylog.info(f"java unCompressURI data: {res}")
            dep_data = self.operateInfo(res)
        # mylog.info(f"dep_data : {dep_data}")
        return dep_data

    def operateInfo(self, res):
        luckysheet_update.update_operate(self.sheet_name, res)
        # 添加多人协同编辑的时候，给其他人选区的位置标红
        # type: # 0：连接成功，1：发送给当前连接的用户，2：发送信息给其他用户，3：发送选区位置信息，999：用户连接断开
        t = res.get("t", None)
        if "mv" == t:
            __type = 3
        else:

            __type = 2
        new_msg = {
            "createTime": int(time.time() * 1000),
            "data": json.dumps(res),
            "id": "%s" % str(self.user),
            "returnMessage": "success",
            "status": "0",
            "type": __type,
            "username": str(self.user)
        }
        return new_msg

class LogConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # self.room_name = self.scope['url_route']['kwargs']['log_file']
        self.room_group_name = 'log_run_info'

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data=None, bytes_data=None):
        message = text_data
        mylog.info(f"receive message: {message}")

        run_log = os.path.join(BASE_DIR, 'logs/RunInfo.log')
        f = open(run_log, 'r', encoding='utf-8')
        f.seek(0, 2)
        while True:
            await asyncio.sleep(1)
            message = f.readlines()
            f.seek(0, 1)
            message = ''.join(message) if message else ''
            if message:
                await self.send(json.dumps({'message': message}))
            else:
                await asyncio.sleep(1)